package com.hfzy.ihk.web.websocket.support.toApp.handler;

import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.web.websocket.constant.Constants;
import com.hfzy.ihk.web.websocket.support.SampleCache;
import com.hfzy.ihk.web.websocket.support.WebSocketManager;
import com.hfzy.ihk.web.websocket.utils.SpringWebSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/29.
 *
 * @author wws
 */
public class AppWebSocketHandler  implements WebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(AppWebSocketHandler.class);

    @Autowired
    private AppWebSocketMessageHandler appWebSocketMessageHandler;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        Map<String,Object> attributes = session.getAttributes();
        String zyUserId = (String)attributes.get("userId");

        //----------------------------先释放旧连接--------------------------------------
        WebSocketSession oldSession = null;
        try {
            oldSession = WebSocketManager.appUserIdOrMacWebSocketSessionMap.get(zyUserId);

            if (oldSession != null) {
                Date connectTime = (Date) oldSession.getAttributes().get("connectTime");
                String sid = oldSession.getId();
                logger.info("关闭旧连接，ID:{},开始连接时间:{},userId:{}",sid, Utils.date2DateTimeString(connectTime), zyUserId);

                //释放旧的连接
                oldSession.close();
            }
        } catch (IOException e) {
            logger.info("释放手机旧的连接有异常");
        }finally {
            oldSession=null;
        }

        //------------------------------------------------------------------
        WebSocketManager.appUserIdOrMacWebSocketSessionMap.put(zyUserId,session);

        Integer count = SampleCache.countConnectTime.get(zyUserId);
        if(count != null) {
            count++;
        }else {
            count=1;
        }

        SampleCache.countConnectTime.put(zyUserId, count);

        logger.info("app 连接完成:userId:{},连接ID:{}，次数:{}",zyUserId,session.getId(),count);

    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

        appWebSocketMessageHandler.handleMessage(session,message);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

        Map<String,Object> attributes = session.getAttributes();
        String userId = (String)attributes.get("userId");
        String token = (String)attributes.get("token");
        String phoneMac = (String)attributes.get("phoneMac");

        logger.debug("handleTransportError: phoneMac:{},userId:{},token:{}, message:{}",phoneMac,userId,token,exception);

       /* try {
            if(session!=null) {
                session.close();
            }
        } catch (IOException e) {
            logger.error("close webSocket failed: userId:{},machineId:{},token:{}, message:{}",userId,token,exception);
        }*/
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        /**删除关系*/
        Map<String,Object> attributes = session.getAttributes();
        String userId = (String)attributes.get("userId");
        Date connectTime = (Date)attributes.get("connectTime");
        String phoneMac = (String)attributes.get("phoneMac");

        String currentCallBrowserSocketInfo = (String)attributes.get("currentCallBrowserSocketInfo");


        WebSocketSession currentSession = WebSocketManager.appUserIdOrMacWebSocketSessionMap.get(userId);
        if(currentSession == session) {

            WebSocketManager.appUserIdOrMacWebSocketSessionMap.remove(userId);

            logger.debug("从数据结构中删除userId-->webSocket的映射,userId:{}",userId);

            logger.info("app连接关闭,ID:{}，userId:{},开始连接时间:{}",session.getId(),userId, Utils.date2DateTimeString(connectTime));

            if(!StringUtil.isEmpty(currentCallBrowserSocketInfo)){

                JSONObject json = JSONObject.parseObject(currentCallBrowserSocketInfo);
                WebSocketSession browserWebSocket = WebSocketManager.browserTokenWebSocketSessionMap.get(json.get("machineFrom"));
                if(browserWebSocket != null && browserWebSocket.isOpen()){

                    json.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE,Constants.WEB_SOCKET_MSG_TYPE_APP_DISCONNECT);
                    json.put(Constants.WEB_SOCKET_JSON_KEY_DESC,"app连接断开");
                    SpringWebSocketUtils.pushToClient(browserWebSocket,json.toJSONString());
                }
            }
        }

        try {
            if (session!=null)
                session.close();
        } catch (IOException e) {
            logger.error("afterConnectionClosed:close webSocket error: userId:{},machineId:{},token:{}, message:{}",userId);
        }

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
